//引入net模块
const net = require('net');
const keyArray = [
    {key: '1', value: "1"},
    {key: 'ff', value: "Connection created successfully"},
    {key: '2', value: "This is the response from 2"},
    {key: '3', value: "text3"},
    {key: '4', value: "text4"},
    {key: '5', value: "text5"},
    {key: '9', value: "success"},
]
const strTohex = (arr)=> {
    arr.push(10)
    return Buffer.from(arr)
}
// 解包
const unPack = (data)=> {
    const datas = Array.prototype.map.call(
        new Uint8Array(data),
        function (bit) {
          return ('00' + bit.toString(16)).slice(-2);
        }
    )
    let str = "";
    for(var i = 0; i < datas.length; i++) {
        str += String.fromCharCode(parseInt(datas[i],16));
    }
    str = str.replace(/\\|\n|\r|\t|\f|\t/g, '').toLowerCase();
    return str
}
// 封包
const packet = (value)=> {
    let str = ""
    let arr = [];
    for(var i = 0; i < value.length; i++) {
        arr.push(value[i].charCodeAt(0))
    }
    return strTohex(arr);
}
//创建TCP服务器
const server = net.createServer(function (socket) {
    //监听data事件
    socket.on("data", (data)=> {
        console.log("客户端数据:", data)
        str = unPack(data);
        // const readSize = socket.bytesRead;
        // let datas = data.toString()
        console.log("客户端数据解包:", str);

        let value = 'ff'
        if(keyArray.find(val=>{return val.key == str})) {
            value = keyArray.find(val=>{return val.key == str})['value']
        }
        console.log("回复数据:", value);
        value = packet(value)
        console.log("回复数据解包:", value);
        
        socket.write(value, function (wb) {
            // const writeSize = socket.bytesWritten;
            console.log("数据发送成功");
        });
    });

    socket.on('timeout', function(timeout) {
        console.log('客户端timeout',timeout);
    });
    socket.on('connect', function(connect) {
        console.log('客户端connect',connect);
    });
    socket.on('close', function(close) {
        console.log('客户端close',close);
    });
    socket.on('end', function(end) {
        console.log('客户端end',end);
    });
});

server.on('listening', function(listening){
    console.log( 'listening事件:',listening)
});
server.on('connection', function(socket){
    console.log('connection事件')
    // socket.end('设备连接');
});
server.on('close', function(close){
    console.log( 'close事件:', close );
});
server.on('error', function(error){
    console.log( 'error事件:', error );
});


const HOST = "192.168.1.3"
const PORT = 9998
//设置监听端口
server.listen(PORT, HOST, function (socket) {
    //获取地址信息
    let address = server.address();
    //获取地址详细信息
    console.log("服务器运行在:http://", address.address+':'+address.port,'类型为:',address.family);
});